'use server';

import { unlink } from 'fs/promises';
import { join } from 'path';
import { revalidateTag } from 'next/cache';
import { signIn } from '@/auth';
import { AuthError } from 'next-auth';
import { z } from 'zod';

const signInSchema = z.object({
    name: z.string({ required_error: '请填写用户名' }).min(1, '请填写用户名'),
    password: z.string({ required_error: '请填写密码' }).min(1, '请填写密码'),
});

// 删除镜像
export async function deleteMirrorAction(filepath: string) {
    try {
        //文件根目录
        const rootPath = join(process.cwd(), process.env.FILE_LOCATION || '/');
        await unlink(join(rootPath, filepath));
        // revalidatePath(`/mirrors/${slug.join('/')}`);
        revalidateTag('mirrors');
        return { success: true };
    } catch (error) {
        return { success: false };
    }
}

// 登录
export async function authenticateAction(prevState: { name?: string[]; password?: string[] } | undefined, formData: FormData) {
    try {
        const name = formData.get('name');
        const password = formData.get('password');
        const validatedFields = signInSchema.safeParse({ name, password });
        if (!validatedFields.success) {
            return validatedFields.error.flatten().fieldErrors;
        }
        await signIn('credentials', {
            name,
            password,
            redirectTo: '/mirrors',
        });
    } catch (error) {
        if (error instanceof AuthError) {
            switch (error.type) {
                case 'CredentialsSignin':
                    return { name: ['用户名、密码验证失败'], password: ['用户名、密码验证失败'] };
                default:
                    return { name: ['未知错误.'], password: ['未知错误.'] };
            }
        }
        throw error;
    }
}
